package cn.youwan.market.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;

import android.util.Log;

import cn.youwan.market.utils.SessionUtils;


/**
 * 
 */
public class HttpTransport {
	private final HttpClient _client;

	public HttpTransport(HttpClient aClient) {
		_client = aClient;
	}

	public String get(boolean proxy, String url, List<NameValuePair> params)
			throws ClientProtocolException, IOException {
		if (proxy) {
			return postByCMCCProxy(url, params);
		} else {
			return get(URI.create(url), params);
		}
	}

	public String post(boolean proxy, String url, List<NameValuePair> params)
			throws ClientProtocolException, IOException {
		if (proxy) {
			Log.i("downs", "true"+url);
			return postByCMCCProxy(url, params);
		} else {
			Log.i("downs", "false"+url);
			return post(URI.create(url), params);
		}
	}

	private String postByCMCCProxy(String url, List<NameValuePair> params)
			throws ClientProtocolException, IOException {
		//HttpHost proxy = new HttpHost("10.0.0.172", 80);
		//_client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		HttpPost post = new HttpPost(url);
//		if (params != null && params.size() > 0) {
//			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
//		}
		HttpResponse httpResponse = _client.execute(post);
		StatusLine statusLine = httpResponse.getStatusLine();
		final int status = statusLine.getStatusCode();
		if (status != 200) {
			throw new IOException();
		} else {
			String s = inputStream2String(httpResponse.getEntity().getContent());
			Log.i("downs", s);
			return s;
		}
	}

	private String post(URI uri, List<NameValuePair> params)
			throws ClientProtocolException, IOException {
		HttpPost post = new HttpPost(uri);
		//TODO 增加用户头
//		String userAgent = MainActivity.USER_AGENT;
//		post.setHeader("user-agent", userAgent);
//		if (params == null) {
//			params = SessionUtils.getHeader();
//		} else {
//			params.addAll(SessionUtils.getHeader());
//		}
//		System.out.println("params:" + params);
//		if (params != null && params.size() > 0) {
//			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
//		}
		HttpContext httpContext = getInstance();
		HttpResponse httpResponse = _client.execute(post, httpContext);
		StatusLine statusLine = httpResponse.getStatusLine();
		final int status = statusLine.getStatusCode();
		if (status != HttpStatus.SC_OK || status == HttpStatus.SC_NOT_MODIFIED) {
			String message = "HTTP Response code: "
					+ statusLine.getStatusCode() + " - "
					+ statusLine.getReasonPhrase();
			System.out.println("=====" + message);
			throw new IOException(message);
		}
		HttpEntity httpEntity = httpResponse.getEntity();
		InputStream is = httpEntity.getContent();
		String string = inputStream2String(is);
		Log.i("yes", string);
		System.out.println("response: " + string + ":response");
		return string;

	}

	private String get(URI uri, List<NameValuePair> params)
			throws ClientProtocolException, IOException {
		HttpGet post = new HttpGet(uri);
		//TODO 增加用户头
//		String userAgent = MainActivity.USER_AGENT;
//		post.setHeader("user-agent", userAgent);
		if (params != null && params.size() > 0) {
			// post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		}
		HttpContext httpContext = getInstance();
		HttpResponse httpResponse = _client.execute(post, httpContext);
		StatusLine statusLine = httpResponse.getStatusLine();
		final int status = statusLine.getStatusCode();
		if (status != HttpStatus.SC_OK || status == HttpStatus.SC_NOT_MODIFIED) {
			String message = "HTTP Response code: "
					+ statusLine.getStatusCode() + " - "
					+ statusLine.getReasonPhrase();
			throw new IOException(message);
		}
		HttpEntity httpEntity = httpResponse.getEntity();
		InputStream is = httpEntity.getContent();
		/*
		 * if (httpEntity.getContentEncoding().getValue().contains("gzip")) {
		 * is= new GZIPInputStream(is); }
		 */
		return inputStream2String(is);

	}

	private static BasicHttpContext httpContext;

	public static BasicHttpContext getInstance() {
		if (httpContext != null) {
			return httpContext;
		}
		httpContext = new BasicHttpContext();
		httpContext.setAttribute(ClientContext.COOKIE_STORE,
				new BasicCookieStore());

		return httpContext;
	}

	private String inputStream2String(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

}
